package com.zhh.front.controller;

import com.zhh.api.service.SmsService;
import com.zhh.common.contants.RedisKey;
import com.zhh.common.enums.RCode;
import com.zhh.common.util.CommonUtil;
import com.zhh.front.view.RespResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Api(tags = "短信业务")
@RestController
@RequestMapping("/v1/sms")
public class SmsController extends BaseController{

    @Resource(name = "smsCodeRegisterImpl")
    private SmsService registerSmsService;

    @Resource(name = "smsCodeLoginImpl")
    private SmsService loginSmsService;

    //注册发送短信验证码
    @GetMapping("/code/register")
    public RespResult sendCodeRegister(@RequestParam String phone){
        RespResult result = RespResult.fail();
        if(CommonUtil.checkPhone(phone)){
            //判断redis中是否已经存在该手机验证码
            String key = RedisKey.KEY_SMS_CODE_REG + phone;
            if(stringRedisTemplate.hasKey(key)){
                result.setRCode(RCode.PHONE_EXISTS); //手机号存在
            }else{
                //发送验证码
                boolean isSuccess = registerSmsService.sendSms(phone);
                if(isSuccess){
                    result = RespResult.ok(); //发送成功
                }
            }
        }else{
            result.setRCode(RCode.PHONE_FORMAT_ERR); //手机号有误
        }
        return result;
    }

    //注册发送短信验证码
    @GetMapping("/code/login")
    public RespResult sendCodeLogin(@RequestParam String phone){
        RespResult result = RespResult.fail();
        if(CommonUtil.checkPhone(phone)){
            //判断redis中是否已经存在该手机验证码
            String key = RedisKey.KEY_SMS_CODE_LOGIN + phone;
            if(stringRedisTemplate.hasKey(key)){
                result.setRCode(RCode.PHONE_EXISTS); //手机号存在
            }else{
                //发送验证码
                boolean isSuccess = loginSmsService.sendSms(phone);
                if(isSuccess){
                    result = RespResult.ok(); //发送成功
                }
            }
        }else{
            result.setRCode(RCode.PHONE_FORMAT_ERR); //手机号有误
        }
        return result;
    }

}

